package com.gege.hmily.account.config;

import com.gege.hmily.exception.DemoError;
import com.gege.hmily.exception.DemoException;
import com.gege.hmily.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @author gechenpeng
 * @date 2019-03-09
 */
@Slf4j
//@RestControllerAdvice
public class AccountExceptionHandler {

    private static final String DELIMITER = ", ";

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse bindException(MethodArgumentNotValidException e) {
        String detailMessage = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(DELIMITER));
        return BaseResponse.error(DemoError.PARAM_INVALID.getErrorCode(),
                DemoError.PARAM_INVALID.getMessage(), detailMessage);
    }

    @ExceptionHandler(DemoException.class)
    public BaseResponse authException(DemoException e) {
        return BaseResponse.error(e);
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse unknownException(Exception e) {
        log.warn("未知异常", e);
        return BaseResponse.error(DemoError.UNKNOWN_ERROR.getErrorCode(),
                DemoError.UNKNOWN_ERROR.getMessage());
    }
}
